﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DataInport
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog dialog = new OpenFileDialog())
            {
                dialog.InitialDirectory = @"E:\1Rice\CSharpDataAccess";
                dialog.Filter = "文本文件|*.txt";
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    txtPath.Text = dialog.FileName;

                    try
                    {
                        //导入数据
                        ImportData(dialog.FileName);
                        MessageBox.Show("导入成功!");
                    }
                    catch
                    {
                        MessageBox.Show("导入失败!");
                    }
                }
            }
        }
        private void ImportData(string fileName)
        {
            string tmp = string.Empty;
            var connStr = ConfigurationManager.AppSettings["connStr"].ToString();

            //读出文件的内容
            //按换行 把每一行作为一条记录
            //按逗号间隔读取每一个字段
            using (StreamReader reader = new StreamReader(fileName, Encoding.UTF8))
            {
                using (SqlConnection conn = new SqlConnection(connStr))
                {
                    using (SqlCommand cmd = conn.CreateCommand())
                    {
                        //执行命令前，打开连接
                        conn.Open();

                        while (!string.IsNullOrEmpty(tmp = reader.ReadLine()))
                        {
                            //每一行分割为一条记录
                            var strArray = tmp.Split('，');
                            var sqlStr = string.Format(@"insert tbl_user values('{0}','{1}',{2},'{3}','{4}','{5}',null)", strArray[0],
                                strArray[1], strArray[2].Trim() == "男" ? 1 : 0, strArray[3], strArray[4], strArray[5]);

                            //执行命令
                            cmd.CommandText = sqlStr;
                            cmd.ExecuteNonQuery();
                        }
                    }
                }
            }
        }
    }
}
